package com.twotiger.and.activity.account.capitalflow;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import app.twotiger.p2p.R;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nineoldandroids.view.ViewPropertyAnimator;
import com.twotiger.and.Constants;
import com.twotiger.and.activity.base.BaseActivity;
import com.twotiger.and.activity.base.BaseHandler;
import com.twotiger.and.adapter.DealDeatilAdapter;
import com.twotiger.and.bean.Basebean;
import com.twotiger.and.bean.DataList;
import com.twotiger.and.bean.Trade;
import com.twotiger.and.util.ArithUtils;
import com.twotiger.and.util.PreferencesUtils;
import com.twotiger.and.util.TimeUtils;
import com.view.pulltorefresh.ILoadingLayout;
import com.view.pulltorefresh.MyListView;
import com.view.pulltorefresh.PullToRefreshBase;
import com.view.pulltorefresh.PullToRefreshBase.OnLastItemVisibleListener;
import com.view.pulltorefresh.PullToRefreshMyListView;

/**
 * 资金流水
 */
public class CapitalFlowPage extends BaseActivity implements OnClickListener {

    private String popupText[] = { "全部资金流水", "充值记录", "投资记录", "提现记录", "还款记录", "奖励记录", "其他" };

    private static final String TAG = "DealDetailPage";
    private static final int GETTRADSLISTSUCCSE = 0;
    private static final int GETTRADSLISTFAIL = 1;
    private PullToRefreshMyListView deal_detail_refresh_list;
    private int pNum = 1;
    private String TAG_refresh = "DealDetailPage_time";
    private HashMap<String, String> params;
    private ArrayList<Trade> trades;
    private DealDeatilAdapter dealDeatilPage;
    private TextView sub_title_center_tv;
    private ImageView sub_title_left_bt;
    private RelativeLayout no_content_rl;
    private TextView tv_available;
    private ImageView iv_no_content;
    private ImageView sub_title_middle_bt;
    private View title;
    private PopupWindow popupWindow;

    private int refreshType; //为-1时，接口取全部数据

    @Override
    protected View loadViewLayout(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.deal_detail_layout, null);
        return view;
    }

    @Override
    protected void findViewById(View view) {
        deal_detail_refresh_list = (PullToRefreshMyListView) view
            .findViewById(R.id.deal_detail_refresh_list);

        title = view.findViewById(R.id.title);
        sub_title_center_tv = (TextView) view.findViewById(R.id.sub_title_center_tv);
        sub_title_left_bt = (ImageView) view.findViewById(R.id.sub_title_left_bt);
        sub_title_middle_bt = (ImageView) view.findViewById(R.id.sub_title_middle_bt);
        sub_title_middle_bt.setVisibility(View.VISIBLE);

        no_content_rl = (RelativeLayout) view.findViewById(R.id.no_content_rl);
        tv_available = (TextView) view.findViewById(R.id.tv_available); //可用余额
        iv_no_content = (ImageView) view.findViewById(R.id.iv_no_content);

        ILoadingLayout endLabels = deal_detail_refresh_list.getLoadingLayoutProxy(false, true);
        endLabels.setPullLabel("向上拉动可以刷新");// 刚上拉时，显示的提示    
        endLabels.setRefreshingLabel("加载中...");// 刷新时    
        endLabels.setReleaseLabel("松开可以刷新");// 上来达到一定距离时，显示的提示
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
        case R.id.sub_title_left_bt:
            onBackPress();
            break;
        case R.id.no_content_rl:
            refreshlist(refreshType);
            break;
        case R.id.sub_title_middle_bt:
        case R.id.sub_title_center_tv:
            doAnim();
            popupWindow.showAsDropDown(title);
            break;
        default:
            break;
        }
    }

    private void doAnim() {
        ViewPropertyAnimator.animate(sub_title_middle_bt).rotationBy(180).setDuration(50);
    }

    private void initPopuWindow() {
        View popupView = LayoutInflater.from(this)
            .inflate(R.layout.capital_flow_popup_layout, null);
        ListView lv_popup = (ListView) popupView.findViewById(R.id.lv_popup);
        SimpleAdapter adapter = new SimpleAdapter(CapitalFlowPage.this, getDataList(),
            R.layout.capital_flow_popup_listl_item, new String[] { "text" },
            new int[] { R.id.tv_item });
        lv_popup.setAdapter(adapter);

        lv_popup.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

                pNum = 1;
                if (0 == arg2) {
                    refreshType = -1;
                    sub_title_center_tv.setText("资金流水");
                    refreshlist(refreshType);
                } else {
                    refreshType = arg2 - 1;
                    sub_title_center_tv.setText(popupText[arg2]);
                    refreshlist(refreshType);
                }
                popupWindow.dismiss();
            }
        });

        popupWindow = new PopupWindow(popupView, LayoutParams.MATCH_PARENT,
            LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(getResources().getDrawable(
            R.drawable.capitalflow_popup_bg));
        popupWindow.setOutsideTouchable(true);
        popupWindow.setAnimationStyle(android.R.style.Animation_Dialog);
        popupWindow.update();
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true);

        popupWindow.setOnDismissListener(new OnDismissListener() {

            @Override
            public void onDismiss() {
                doAnim();
            }
        });

    }

    private List<Map<String, String>> getDataList() {
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        Map<String, String> map = null;
        for (int i = 0; i < popupText.length; i++) {
            map = new HashMap<String, String>();
            map.put("text", popupText[i]);
            list.add(map);
        }
        return list;
    }

    @Override
    protected void setListener() {
        deal_detail_refresh_list.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

            @Override
            public void onLastItemVisible() {
                String footerContent = ((TextView) deal_detail_refresh_list
                    .getChildviewOfFooterview()).getText().toString();
                if ("已无更多项目".equals(footerContent)) {
                    return;
                }
                /**
                 * 加载更多数据
                 */
                pNum++;
                refreshlist(refreshType);
            }
        });
        deal_detail_refresh_list
            .setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<MyListView>() {
                @Override
                public void onPullDownToRefresh(PullToRefreshBase<MyListView> refreshView) {
                    /**
                     * 刷新数据
                     */
                    pNum = 1;
                    refreshlist(refreshType);
                }

                @Override
                public void onPullUpToRefresh(PullToRefreshBase<MyListView> refreshView) {
                    /**
                    * 加载更多数据
                    */
                    pNum++;
                    refreshlist(refreshType);
                }
            });

        handler = new BaseHandler(this) {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case GETTRADSLISTSUCCSE:
                    Basebean result = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result.isOk()) {
                        deal_detail_refresh_list.getLoadingLayoutProxy().setLastUpdatedLabel(
                            "最后更新：今天 " + TimeUtils.getFormatDate(" HH:mm"));
                        DataList dataList = JSON.parseObject(result.data, DataList.class);
                        ArrayList<Trade> tradelist = (ArrayList<Trade>) JSON.parseArray(
                            dataList.getList(), Trade.class);
                        if (!tradelist.isEmpty()) {
                            if (tradelist.size() < Integer.parseInt(Constants.pageSize)) {
                                deal_detail_refresh_list.changeMyFooterViewContent(false);
                            } else {
                                deal_detail_refresh_list.changeMyFooterViewContent(true);
                            }
                            no_content_rl.setVisibility(View.GONE);
                            if (pNum == 1) {
                                dealDeatilPage.resetData(tradelist);
                            } else {
                                dealDeatilPage.addData(tradelist);
                            }
                            if (refreshType != -1) {
                                dealDeatilPage.setHeader(false);
                            } else {
                                dealDeatilPage.setHeader(true);
                            }
                        } else {
                            //请求数据是空的
                            if (pNum == 1) {
                                no_content_rl.setVisibility(View.VISIBLE);
                                iv_no_content.setImageResource(R.drawable.no_content);
                            } else {
                                //                                showToast("没有更多数据");
                                deal_detail_refresh_list.changeMyFooterViewContent(false);
                                dealDeatilPage.notifyDataSetChanged();
                            }
                        }
                    } else {
                        showToast(result.codeDesc);
                    }

                    deal_detail_refresh_list.onRefreshComplete();
                    break;
                case GETTRADSLISTFAIL:
                    showToast("网络不佳，请重试");
                    deal_detail_refresh_list.onRefreshComplete();
                    break;
                default:
                    break;
                }
                super.handleMessage(msg);
            }
        };
        sub_title_left_bt.setOnClickListener(this);
        no_content_rl.setOnClickListener(this);
        sub_title_middle_bt.setOnClickListener(this);
        sub_title_center_tv.setOnClickListener(this);
    }

    private void refreshlist(int type) {
        params.clear();
        params.put("token", getToken());
        params.put("pageNum", String.valueOf(pNum));
        params.put("pageSize", Constants.pageSize);
        params.put("timestamp", TimeUtils.getTimeStamp());
        if (type != -1) {
            params.put("type", String.valueOf(type));
        }
        getDate(params, Constants.ASSETRECORDQUERY, handler, GETTRADSLISTSUCCSE, GETTRADSLISTFAIL,
            true, true, false);
    }

    @Override
    protected void processLogic() {

        refreshType = getIntent().getIntExtra("REFRESHTYPE", -1);

        initPage();
        trades = new ArrayList<Trade>();
        dealDeatilPage = new DealDeatilAdapter(CapitalFlowPage.this, trades);
        deal_detail_refresh_list.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        deal_detail_refresh_list.setAdapter(dealDeatilPage);
        initData();

        initPopuWindow();
    }

    public void initData() {
        refreshlist(refreshType);
    }

    private void initPage() {
        params = getParm();
        sub_title_left_bt.setVisibility(View.VISIBLE);
        if (refreshType == -1) {
            sub_title_center_tv.setText("资金流水");
        } else {
            sub_title_center_tv.setText(popupText[refreshType + 1]);
        }
        tv_available.setText(ArithUtils.coverMoneyComma(CapitalFlowPage.this.application
            .getUserAsset().avaliable + ""));
    }

    @Override
    protected void onBackPress() {
        finish();
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);

    }

}
